import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";


export const useCartStore = defineStore('cart', () => {
    let userStore = useUserStore()
    // 判断是否登录（计算属性，有token返回true）
    let isLogin = computed(() => userStore.userInfo.token)

    const cartList = ref([])
    // 加入购物车
    const addCart = async (goods) => {
        // 解构出来
        let { skuId, count } = goods
        if (isLogin.value){
            // 已经登录，调接口把数据上传
            await insertCartAPI({ skuId, count })
            // 请求接口获取最新的购物车数据
            updateNewList()
        }else{
            // 没登录，本地保存数据
            let findRes = cartList.value.find((item) => goods.skuId === item.skuId)
            if (findRes) {
                // 购物车有，则数量加一
                findRes.count++
            } else {
                cartList.value.push(goods)
            }
        }
    }

    // 调接口获取最新的购物车数据
    let updateNewList = async () => {
        let res = await findNewCartListAPI()
        cartList.value = res.result
    }

    // 删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value){
            await delCartAPI([skuId])
            // 请求接口获取最新的购物车数据
            updateNewList()
        }else{
            let findArr = cartList.value.filter(item => item.skuId != skuId)
            cartList.value = findArr
        }
    }

    // 计算属性
    // 计算数量
    let allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 计算总价格
    let allPrice = computed(() => cartList.value.reduce((a, c) => a + (c.count * c.price), 0))

    // 单选功能
    let singleCheck = (skuId, selected) => {
        let findItem = cartList.value.find(item => item.skuId == skuId)
        findItem.selected = selected
    }

    // 是否全选
    let isAll = computed(() => cartList.value.every(item => item.selected))
    // 设置全选
    let allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected);
    }


    // 计算已选择数量
    let selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 计算已选择的总价格
    let selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + (c.count * c.price), 0))

    // 清除购物车
    let clearCart = () => {
        cartList.value = []
    }


    return{
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }
}, {
    persist: true
})



